import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/base/base_basic_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/setting/setting_form/setting_form_widget.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/toast_utils.dart';

class BasicInfoController extends BaseBasicController {
  var actionKey = GlobalKey();
  var formKey = GlobalKey<FormState>();
  var settingFormKey = GlobalKey<SettingFormWidgetState>();

  DeviceServices deviceServices = DeviceServices();
  // tag 控制器
  BrnDeleteTagController deleteTagController = BrnDeleteTagController();
  // mqtt密码控制器
  TextEditingController pwdController = TextEditingController();
  // mqtt用户名控制器
  TextEditingController nameController = TextEditingController();
  // 电流变比
  TextEditingController currentController = TextEditingController();
  // 电压变比
  TextEditingController voltageController = TextEditingController();
  // 电能变比
  TextEditingController electricController = TextEditingController();
  // 功率变比
  TextEditingController poweController = TextEditingController();
  // 第三方站点
  Map? thirdSite;
  // 已的选择设备
  List<Map> selectDevice = [];
  // 当前选择的设备，（还未通过请求加进去）
  List curSelectDevice = [];
  // 第三方站点列表
  List? thirdSiteList;

  @override
  void onInit() {
    super.onInit();

    deviceId = Get.arguments['deviceId'];

    title = Get.arguments['deviceName'];
    getDeviceInfo();
  }

  bool validateMqtt(BuildContext context) {
    var name = nameController.text;
    var pwd = pwdController.text;
    if (name.isEmpty) {
      BrnToast.show(
        ResKey.plsEnterMqttUsername.tr,
        context,
      );
    } else if (pwd.isEmpty) {
      BrnToast.show(
        sprintf(
            ResKey.fieldRequiredSentence.tr, ['mqtt ${ResKey.userName.tr}']),
        context,
      );
    } else if (!(RegExp(
                r'^(?![0-9]+$)(?![a-zA-Z]+$)(?![^a-zA-Z0-9]+$)[^\u4e00-\u9fa5 ]{8,100}$')
            .hasMatch(pwd) &&
        pwd.length > 7)) {
      BrnToast.show(
        "密码至少八位由字符和数字组成",
        context,
      );
    } else {
      return true;
    }
    return false;
  }

  setMqtt(BuildContext context) {
    if (validateMqtt(context)) {
      configCommuniactionInfo(
          {'userName': nameController.text, 'password': pwdController.text},
          context);
    }
  }

  setMeter(BuildContext context) {
    if (validateMqtt(context)) {
      if (currentController.text.isEmpty) {
        BrnToast.show(
          sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.currentRatio.tr]),
          context,
        );
      } else if (voltageController.text.isEmpty) {
        BrnToast.show(
          sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.voltageRatio.tr]),
          context,
        );
      } else if (electricController.text.isEmpty) {
        BrnToast.show(
          sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.electricRatio.tr]),
          context,
        );
      } else if (poweController.text.isEmpty) {
        BrnToast.show(
          sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.powerRatio.tr]),
          context,
        );
      } else {
        configCommuniactionInfo({
          'userName': nameController.text,
          'password': pwdController.text,
          'currentRatio': currentController.text,
          'voltageRatio': voltageController.text,
          'energyRatio': electricController.text,
          'powerRatio': poweController.text
        }, context);
      }
    }
  }

  setVoltageAndCurent(BuildContext context, Map<String, dynamic> params) {
    if (FuncUtils.isEmpty(params['voltageRatio'])) {
      return BrnToast.show(
        sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.voltageRatio.tr]),
        context,
      );
    } else if (FuncUtils.isEmpty(params['currentRatio'])) {
      return BrnToast.show(
        sprintf(ResKey.fieldRequiredSentence.tr, [ResKey.electricRatio.tr]),
        context,
      );
    }
    configCommuniactionInfo(params, context);
  }

  setIntervert(BuildContext context) {
    if (thirdSite == null) {
      BrnToast.show(
        '${ResKey.pleSelect.tr} ${ResKey.thirdPartySite.tr}',
        context,
      );
    } else {
      configCommuniactionInfo({
        'thirdSiteId': thirdSite!['id'],
      }, context);
    }
  }

  toSelectSite(BuildContext context) async {
    if (thirdSiteList == null) {
      await getThirdSite();
    }
    List<String> list = [];
    if (thirdSiteList != null) {
      list = thirdSiteList!.map((e) => e['siteName'].toString()).toList();
      BrnMultiDataPicker(
        context: Get.context!,
        title: ResKey.selectSite.tr,
        confirmClick: (indexList) {
          thirdSite = thirdSiteList![indexList[0]];
          update();
        },
        delegate: Brn1RowDelegate(list),
      ).show();
    }
  }

  configCommuniactionInfo(Map config, BuildContext context) =>
      Configs.httpClient.requestWithLoading(() async {
        Get.back();
        var param = {
          'deviceId': device?.deviceId,
          'paramConfigType': device?.paramConfigType,
          'config': jsonEncode(config),
          'productId': device?.productId
        };
        print('param:${jsonEncode(param)}');
        await deviceServices.updateDeviceCommunicationConfigNoAuth(param);

        await getDeviceInfo(showLoading: false);
        dismissLoading();
        TotastUtils.success(context,
            title: ResKey.mineUserManagerSaveSuccess.tr);
      }, showLoading: true);

  toSelectDevice() {
    Get.toNamed(RouterPath.subDeviceTree, arguments: {
      'siteId': device?.siteId,
      'selectDeviceIds': curSelectDevice
    })?.then((value) {
      if (value is List<Map>) {
        curSelectDevice = value;
        deleteTagController.clear();
        deleteTagController
            .addTags(value.map((e) => e['name'] as String).toList());
      }
    });
  }

  Future getThirdSite() async => await Configs.httpClient.requestWithLoading(
        () async {
          var data = await services.getThirdSiteList({
            'current': 1,
            'pageSize': 10000,
            'productId': device?.productId
          });
          thirdSiteList = data['list'];
        },
      );

  closeForm() {
    nameController.text = '';
    pwdController.text = '';
    currentController.text = '';
    voltageController.text = '';
    electricController.text = '';
    poweController.text = '';
    thirdSite = null;
    Get.back();
  }

  associateDevice() => Configs.httpClient.requestWithLoading(() async {
        var param = {
          'deviceId': device?.deviceId,
          'associateIds': curSelectDevice.map((e) => e['id']).toList(),
          'type': device?.productConfigType
        };
        await deviceServices.addDeviceAssociate(param);
        Get.back();
        TotastUtils.success(Get.context!,
            title: ResKey.mineUserManagerSaveSuccess.tr);
      });

  Future getAssociateDevice() async =>
      await Configs.httpClient.requestWithLoading(() async {
        var data = await deviceServices.getAssociateDevicesByDeviceIdAndType(
            {'deviceId': device?.deviceId, 'type': device?.productConfigType});

        selectDevice = List.of(data)
            .map((e) => {
                  'id': e['deviceId'],
                  'name': e['name'],
                })
            .toList();

        deleteTagController
            .addTags(selectDevice.map((e) => e['name'] as String).toList());
      });
}
